import 'package:flutter/material.dart';
import 'package:hxdj/common/dio/dio_http.dart';
import 'package:hxdj/common/my_constant.dart';
import 'package:hxdj/common/my_get_it.dart';
import 'package:hxdj/message/rongcloud/chat/rc_chat_global_viewmodel.dart';
import 'package:hxdj/message/rongcloud/rc_chat/model/rc_chat_model.dart';
import 'package:hxdj/message/rongcloud/rc_engine_manager.dart';
import 'package:rongcloud_im_wrapper_plugin/rongcloud_im_wrapper_plugin.dart';

class RCChatSeparateViewModel extends ChangeNotifier {
  final RCChatGlobalModel globalModel = serviceLocator<RCChatGlobalModel>();

  String targetId = '';

  //是否更多数据
  bool haveMoreData = false;

  RCChatSeparateViewModel(String tarId) {
    globalModel.clearData();
    targetId = tarId;
    getMessages();
  }
  //获取与当前人的聊天信息
  getMessages({int? timestamp}) async {
    if (timestamp == null) {
//获取与当前人的聊天信息
      Map<String, dynamic> imUserInfo = await requestIMUserInfo(targetId);
      globalModel.imUserInfo = imUserInfo;
    }

    //获取与某人的消息记录 加载历史消息
    RCEngineManager().getMessages(targetId,
        timestamp: timestamp ?? DateTime.now().microsecondsSinceEpoch,
        callback: IRCIMIWGetMessagesCallback(onSuccess: (List<RCIMIWMessage>? value) {
          List<ChatMessageBaseModel> valueList = [];
          value?.forEach((RCIMIWMessage element) {
            ChatMessageBaseModel? messageModel;
            switch (element.messageType) {
              case RCIMIWMessageType.text:
                messageModel = ChatMessageTextModel.fromJson(element.toJson());
                break;
              case RCIMIWMessageType.image:
                messageModel = ChatMessageImageModel.fromJson(element.toJson());
                break;
              default:
                messageModel = ChatMessageBaseModel.fromJson(element.toJson());
            }

            valueList.add(messageModel);
          });


          if (valueList.length < MyConstant.messagePageSize) {
            haveMoreData = false;
          } else {
            haveMoreData = true;
          }
          print("haveMoreData === ${haveMoreData}");

          valueList.toList();
          globalModel.setMessageList(targetId, valueList);
        }, onError: (int? code) {
          debugPrint("历史消息有多少 code $code");
        }));
  }

  //获取IMUser的详情
  Future<Map<String, dynamic>> requestIMUserInfo(String imUser) async {
    // 去请求服务器数据.
    Map<String, dynamic> resultMap = await DioHttpManager()
        .request(MyApi.getUserInfoByImuser, method: DioHttpManager.post, data: {"im_user": imUser, "index_type": 2});

    if (resultMap["code"] == 0) {
      Map<String, dynamic> dataMap = resultMap["data"];

      final String tid = (dataMap["t_id"] ?? "").toString();
      if (tid.isNotEmpty) {
        dataMap['headImageName'] = dataMap['t_member_img'];
      } else {
        dataMap['headImageName'] = dataMap['member_img'];
      }
      return dataMap;
    }
    return {"nickname": imUser, "headImageName": ""};
  }
}
